#公共模块，作用，连接数据库，执行增删改
import pymysql
user_name=''#全局变量，用于存储登陆的用户
#打开数据库
def open():
    db=pymysql.connect(host='127.0.0.1',user='root',passwd='1234',
                       db='student_sys')
    #print(db)
    return db
def execute_sql(sql,values=()):
    db=open()#获取连接对象
    cursor=db.cursor() #创建游标对象
    try:
        cursor.execute(sql,values)
        db.commit() #事务的提交
        return True
    except Exception as e:
        print(e)
        db.rollback()#事务的回滚
        return False
    finally:
        cursor.close()
        db.close()

#查询操作，模糊查询
def query_sql(sql,*params):
    db=open()
    cursor=db.cursor()
    cursor.execute(sql,params)
    result=cursor.fetchall()#查询全部
    cursor.close()
    db.close()
    return result

def query(sql):
    db = open()
    cursor = db.cursor()
    cursor.execute(sql)
    result = cursor.fetchall()  # 查询全部
    cursor.close()
    db.close()
    return result

# if __name__ == '__main__':
#     #测试
#     # sql='insert into tb_user values (%s,%s)'
#     # execute_sql(sql,('ysj','ysj'))
#     # sql='select * from tb_user where username=%s and userpwd=%s'
#     # print(query_sql(sql,'ysj','ysj'))
#     # sql='select * from tb_user'
#     # print(query(sql))
#     sql = 'select * from tb_grade'
#     print(query(sql))
